// pages/index/index.js
const app = getApp()

Page({
  data: {
    banners: [],
    categories: [],
    featuredFlowers: [],
    hotFlowers: [],
    loading: false
  },

  onLoad() {
    this.loadData();
  },

  onShow() {
    // 更新自定义tabBar的选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      });
    }
    // 更新购物车数量
    app.getCartCount()
  },

  onPullDownRefresh() {
    this.loadData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    // 可以在这里加载更多数据
  },

  // 加载页面数据
  // 加载页面数据
  async loadData() {
    this.setData({ loading: true })
    
    try {
      await Promise.all([
        this.loadBanners(),
        this.loadCategories(),
        this.loadFeaturedFlowers(),
        this.loadHotFlowers()
      ])
    } catch (error) {
      console.error('加载数据失败:', error)
      app.showToast('加载失败，请重试', 'none')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载轮播图（使用推荐商品）
  async loadBanners() {
    try {
      const response = await app.request({
        url: '/flowers/featured/',
        data: { limit: 3 }
      })
      
      if (response.success) {
        const banners = response.data.map(flower => ({
          id: flower.id,
          image: flower.main_image,
          title: flower.name
        }))
        this.setData({ banners })
      }
    } catch (error) {
      console.error('加载轮播图失败:', error)
    }
  },

  // 加载分类
  async loadCategories() {
    try {
      const response = await app.request({
        url: '/flowers/categories/'
      })
      
      if (response.success) {
        this.setData({
          categories: response.data.slice(0, 4) // 只显示前4个分类
        })
      }
    } catch (error) {
      console.error('加载分类失败:', error)
    }
  },

  // 加载推荐商品
  async loadFeaturedFlowers() {
    try {
      const response = await app.request({
        url: '/flowers/featured/',
        data: { limit: 6 }
      })
      
      if (response.success) {
        this.setData({
          featuredFlowers: response.data
        })
      }
    } catch (error) {
      console.error('加载推荐商品失败:', error)
    }
  },

  // 加载热销商品
  async loadHotFlowers() {
    try {
      const response = await app.request({
        url: '/flowers/hot/',
        data: { limit: 8 }
      })
      
      if (response.success) {
        this.setData({
          hotFlowers: response.data
        })
      }
    } catch (error) {
      console.error('加载热销商品失败:', error)
    }
  },

  // 搜索点击
  onSearchTap() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  // 分类点击
  onCategoryTap(e) {
    const categoryId = e.currentTarget.dataset.id
    wx.switchTab({
      url: '/pages/category/category'
    })
    
    // 通过事件通知分类页面
    setTimeout(() => {
      wx.getApp().globalData.selectedCategoryId = categoryId
    }, 100)
  },

  // 分类更多点击
  onCategoryMoreTap() {
    wx.switchTab({
      url: '/pages/category/category'
    })
  },

  // 商品点击
  onProductTap(e) {
    const productId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/detail/detail?id=${productId}`
    })
  },

  // 更多点击
  onMoreTap(e) {
    const type = e.currentTarget.dataset.type
    let url = '/pages/category/category'
    
    if (type === 'featured') {
      url += '?featured=1'
    } else if (type === 'hot') {
      url += '?hot=1'
    }
    
    wx.switchTab({
      url: '/pages/category/category'
    })
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '花仙馆 - 精美鲜花，传递美好',
      path: '/pages/index/index',
      imageUrl: 'https://flower-1.oss-cn-shanghai.aliyuncs.com/share/share-index.jpg'
    }
  },

  onShareTimeline() {
    return {
      title: '花仙馆 - 精美鲜花，传递美好',
      imageUrl: 'https://flower-1.oss-cn-shanghai.aliyuncs.com/share/share-index.jpg'
    }
  }
})
